/**
 * 
 */
package com.zjtobacco.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.zjtobacco.domain.User;
import com.zjtobacco.service.UserService;

/**
 * @author junpingwang
 * 
 */
public class GradRealm extends AuthorizingRealm {
	@Autowired
	private UserService userService;

	public GradRealm() {
		super();
		// 设置认证token的实现类
		setAuthenticationTokenClass(UsernamePasswordToken.class);
		// 设置加密算法
		setCredentialsMatcher(new HashedCredentialsMatcher(
				Md5Hash.ALGORITHM_NAME));

	}

	// 授权
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principalCollection) {
		String loginName = (String) principalCollection.fromRealm(getName())
				.iterator().next();
		if (!loginName.equals("admin")) {
			return null;
		}
		SimpleAuthorizationInfo result = new SimpleAuthorizationInfo();

		// result.addRoles(UserRoles.findRoleNamesOf(user));
		// for (Role role : UserRoles.findRolesOf(user)) {
		// result.addStringPermissions(role.getPermissions());
		// }

		return result;

	}

	// 认证
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken upToken = (UsernamePasswordToken) token;
		String username = upToken.getUsername();
		try {
			User user = userService.getByUsername(username);
			if (user != null) {
				return new SimpleAuthenticationInfo(username,
						user.getPassword(), getName());
			} else {
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

}